const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            checkList: [],
            xlsx_config: [],
            Sortable: null,
            base_cycle:[],
            xlsx_table_type:[],
            government_agencies:[]
        };
    },
    mounted() {
        this.getCategory();
        this.$nextTick(() => { //拖拽排序
            var $ul = document.querySelector('#Sortable');
            $ul.addEventListener('selectstart', function (e) {
                e.preventDefault();
            })
            this.Sortable = Sortable.create($ul, {
                handle: '.el-checkbox',
                draggable: '.el-checkbox',
                animation: 150,
                onUpdate: (event) => {
                    let newIndex = event.newIndex, oldIndex = event.oldIndex;
                    $li = $ul.children[newIndex], $oldLi = $ul.children[oldIndex]
                    //先删除移动的节点, 再插入移动的节点到原有节点，还原了移动的操作
                    $ul.removeChild($li)
                    if (newIndex > oldIndex) {
                        $ul.insertBefore($li, $oldLi)
                    } else {
                        $ul.insertBefore($li, $oldLi.nextSibling)
                    }
                    //通过改变vue遍历数组移动节点
                    let item = this.checkList[oldIndex];
                    this.checkList.splice(oldIndex, 1);
                    this.checkList.splice(newIndex, 0, item);
                }
            })
        })
    },
    computed: {
        CREATE_TABLE() {
            let systemList = [
                { COLUMN_NAME: 'Creater_SerialNumber', COLUMN_DEFAULT: '', COLUMN_COMMENT: '创建人' },
                { COLUMN_NAME: 'Create_Datetime', COLUMN_DEFAULT: '', COLUMN_COMMENT: '创建时间' },
                { COLUMN_NAME: 'Row_Status', COLUMN_DEFAULT: '', COLUMN_COMMENT: '行状态' },
                { COLUMN_NAME: 'Operation_ID', COLUMN_DEFAULT: '', COLUMN_COMMENT: '操作人' },
                { COLUMN_NAME: 'Operation_Datetime', COLUMN_DEFAULT: '', COLUMN_COMMENT: '操作时间' }
            ]
            const Xlsx_Table_SerialNumber = 'xlsx_ledger_' + (+new Date());
            //表名 CREATE TABLE省略
            let SQL = "`" + Xlsx_Table_SerialNumber + "` (\r\n" + "`XLSX_SerialNumber` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '流水号',\r\n";
            //字段
            [...this.checkList, ...systemList].forEach(item => {
                SQL = SQL + "`" + item.COLUMN_NAME + "` " + "varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '" + item.COLUMN_DEFAULT + "' COMMENT '" + item.COLUMN_COMMENT + "',\r\n";
            })
            //主键
            SQL = SQL + "PRIMARY KEY (`XLSX_SerialNumber`)\r\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='" + this.dataForm.Xlsx_File_Name + "';";
            return { Xlsx_Table_SerialNumber, SQL }
        }
    },
    methods: {
        getCategory() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'base_cycle',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.base_cycle = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'xlsx_config',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.xlsx_config = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'xlsx_table_type',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.xlsx_table_type = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/permissionsTree/getGovernment_Agencies_TreeByPermissions`,
                type: "GET",
                data: {
                    Government_AgenciesCode: getCookie('unit'), //请求参数
                },
                success:  (data)=> {
                  this.government_agencies = data;
                },
                complete: (XMLHttpRequest) => {
                  requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
           
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                const { Xlsx_Table_SerialNumber, SQL } = this.CREATE_TABLE;
                this.dataForm.Xlsx_Table_SerialNumber = Xlsx_Table_SerialNumber;
                this.dataForm.Children = {
                    xlsx_table_log: [{
                        Xlsx_Table_SerialNumber,
                        Xlsx_SQL_Main: window.btoa(unescape(encodeURIComponent(SQL))),
                        Operation_IP: getIpAddress(),
                    }]
                }
                lJSONObject_DataSet = {
                    Add: {
                        xlsx_table: [this.dataForm],
                        document_rule: [{
                            Document_Name: Xlsx_Table_SerialNumber,
                            Document_Head: 'XL',
                            Document_SerialNumber: '0',
                            Document_Length: '15'
                        }]
                    }
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {
                        
                        $.ajax({
                            headers: requestHeaders(),
                            url: `${mh}/generalBusiness/generalDataTableOperation`,
                            type: 'POST',
                            data: {
                                Data: SQL
                            },
                            success: (res) => {
                                if (res.Status === 'success') {
                                    this.$message.success("提交成功")
                                    window.location.href = './index.html'
                                } else {
                                    this.$message.error("提交失败，请稍后再试")
                                }
                            },
                            complete: (XMLHttpRequest) => {
                                this.loading = false
                                requestPretreatment(XMLHttpRequest);
                            },
                            dataType: "json"
                        })
                    } else {
                        this.loading = false;
                    }
                })
                // $.ajax({
                //     headers: requestHeaders("JSON"),
                //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                //     method: "post",
                //     data: JSON.stringify({
                //         Data: lJSONObject_DataSet,
                //     }),
                //     success: (res) => {
                //         if (res.Status == 'success') {
                //             $.ajax({
                //                 headers: {
                //                     "content-type": "application/x-www-form-urlencoded",
                //                     "Session": 'session5'
                //                 },
                //                 url: `${y}/generalDataTableOperation`,
                //                 type: 'POST',
                //                 data: {
                //                     Data: SQL
                //                 },
                //                 success: (res) => {
                //                     if (res.Status === 'success') {
                //                         this.$message.success("提交成功")
                //                         window.location.href = './index.html'
                //                     } else {
                //                         this.$message.error("提交失败，请稍后再试")
                //                     }
                //                 },
                //                 complete: (XMLHttpRequest) => {
                //                     this.loading = false
                //                 },
                //                 dataType: "json"
                //             })
                //         } else {
                //             this.loading = false;
                //         }
                //     },
                //     complete: (XMLHttpRequest) => {
                //         requestPretreatment(XMLHttpRequest)
                //     }
                // });
            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-cascader', ylCascader)
app.component('yl-text-editor', ylTextEditor);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
